package com.example.demo.cim.client.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.cim.client.service.RouteRequest;
import com.example.demo.cim.client.vo.req.GroupReqVO;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @author ：Anitaxiaofeng
 * @description：
 * @create 2019-01-23
 **/
@Service
public class RouteRequestImpl implements RouteRequest {

    private final static Logger LOGGER = LoggerFactory.getLogger(RouteRequestImpl.class);

    private MediaType mediaType = MediaType.parse("application/json");



    @Autowired
    private OkHttpClient okHttpClient;

    @Value("${cim.group.route.request.url}")
    private String groupRouteRequestUrl;

    @Override
    public void sendGroupMsg(GroupReqVO groupReqVO) throws Exception {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("msg", groupReqVO.getMsg());
        jsonObject.put("userId", groupReqVO.getUserId());
        RequestBody requestBody = RequestBody.create(mediaType, jsonObject.toString());
        Request request = new Request.Builder()
                .url(groupRouteRequestUrl)
                .post(requestBody)
                .build();

        Response response =  okHttpClient.newCall(request).execute();
        try {
            if (!response.isSuccessful()){
                throw new IOException("Unexpected code " + response);
            }
        }finally {
            response.body().close();
        }
    }
}
